package com.cw.realtime.common
package util

import constant.Constant
import constant.Constant.HBASE_NAMESPACE

import io.circe.parser
import io.circe.syntax._
import org.apache.hadoop.hbase.client.Connection
import redis.clients.jedis.{Jedis, JedisPool, JedisPoolConfig}

import scala.util.Try

object RedisUtil {

  private val conf = new JedisPoolConfig
  conf.setMaxIdle(10)
  conf.setMaxTotal(300)
  conf.setMinIdle(2)
  conf.setTestOnCreate(true)
  conf.setTestOnBorrow(true)
  conf.setTestOnReturn(true)
  conf.setMaxWaitMillis(10 * 1000)
  private val pool = new JedisPool(conf, "hadoop02", 6379)

  def getJedis: Option[Jedis] = {
    Try(pool.getResource).toOption
  }


  def closeJedis(jedis: Option[Jedis]): Unit = {
    jedis.foreach {
      _.close()
    }
  }

  def getRedisKey(tableName: String, rowkey: String): String =
    Constant.HBASE_NAMESPACE + ":" + tableName + ":" + rowkey

}


class Cache4Dim {
  private val j = RedisUtil.getJedis
  private val conn = HbaseUtil.getConnection

  private def getHbaseCell(c: Connection, tableName: String, rowkey: String): Map[String, String] = {
    HbaseUtil.getCells(c, HBASE_NAMESPACE, tableName, rowkey, "info")
  }


  def close(): Unit = {
    RedisUtil.closeJedis(j)
    HbaseUtil.closeConnection(conn)
  }

  def get(tableName: String, rowkey: String): Map[String, String] = (j, conn) match {

    case (Some(jedis), Some(c)) =>
      // 尝试获取redis缓存
      val key = RedisUtil.getRedisKey(tableName, rowkey)
      Option(jedis.get(key)) match {
        // redis中有缓存
        case Some(jsonStr) =>
          println("redis缓存 ========>" + jsonStr)
          parser.parse(jsonStr).toOption.get.asObject.get.toMap.mapValues(_.asString.get)
        // redis中无缓存
        case None =>
          val cell = getHbaseCell(c, tableName, rowkey)
          jedis.setex(key, 60 * 60, cell.asJson.noSpaces)
          cell
      }

    case (None, Some(c)) =>
      getHbaseCell(c, tableName, rowkey)

    case _ => throw new RuntimeException("没有可用的Hbase连接")
  }
}

